package www.dianbaozu.com.ui.manage

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import androidx.annotation.NonNull
import androidx.core.widget.doOnTextChanged
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.RecyclerView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.module.LoadMoreModule
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.scwang.smart.refresh.layout.SmartRefreshLayout
import com.scwang.smart.refresh.layout.api.RefreshLayout
import dagger.hilt.android.AndroidEntryPoint
import www.dianbaozu.com.R
import www.dianbaozu.com.databinding.FragmentSearchMemberUserApiBinding
import www.wen.com.common.lib.base.fragment.BaseListFragment
import www.wen.com.common.lib.base.module.BaseViewModel
import www.wen.com.common.lib.data.entities.RequestBodyParameter
import www.wen.com.common.lib.data.entities.ServiceMemberEntity
import www.wen.com.common.lib.data.entities.ServiceMemberListEntity
import www.wen.com.common.lib.extension.glide.setImageUrl
import www.wen.com.common.lib.extension.imgUrl
import www.wen.com.common.lib.extension.nav
import www.wen.com.common.lib.extension.observeObject
import www.wen.com.common.lib.helper.loading.KeyHelper
import www.wen.com.common.lib.helper.loading.KeyHelper.BUNDLE_DATA
import www.wen.com.common.lib.helper.loading.TitleBarUniversalAdapter
import www.wen.com.common.lib.util.KeyboardUtils

/**
 * @author WEN
 * @Description:使用服务器自带的接口管理成员
 * @date 2020//25 17:48
 */
@AndroidEntryPoint
class SearchMemberUseApiFragment :
        BaseListFragment<FragmentSearchMemberUserApiBinding, ServiceMemberListEntity, ServiceMemberEntity>() {

    private lateinit var mAdapter: RecommendationServerAdapter

    private lateinit var mRequestBodyParameter: RequestBodyParameter

    private val findMemberUseApiViewModel: FindMemberUseApiViewModel by viewModels()

    override val viewModel: BaseViewModel
        get() = findMemberUseApiViewModel

    override val mSmartRefreshLayout: SmartRefreshLayout
        get() = dataBinding.smartRefreshLayout

    override fun isEnableLoadingHelper(): Boolean = true

    override fun getTitleBarUniversalAdapter(): TitleBarUniversalAdapter =
            TitleBarUniversalAdapter(requireActivity(), "成员", action = ::titleAction)

    override fun getLayoutId(): Int = R.layout.fragment_search_member_user_api

    override fun lazyInitView() {
        super.lazyInitView()
        mRequestBodyParameter = requireArguments().getParcelable(BUNDLE_DATA)!!
        observeListen()
        launchRequest(false)
        dataBinding.run {
            etSearch.doOnTextChanged { text, _, _, _ ->
                if (text.toString().isBlank()) {
                    launchRequest(true, null)
                } else {
                    launchRequest(true, text.toString())
                }
            }
            etSearch.post {
                KeyboardUtils.showSoftInput(etSearch)
            }
        }

    }

    private fun observeListen() {
        findMemberUseApiViewModel.uiState.observe(this) {
            if (it.showSuccess != null) {
                if (it.isRefresh) {
                    if (it.showSuccess!!.isEmpty()) {
                        mAdapter.setList(null)
                        mAdapter.setEmptyView(
                                LayoutInflater.from(requireActivity())
                                        .inflate(R.layout.layout_empty, null, false)
                        )
                    } else {
                        mAdapter.setList(it.showSuccess)
                    }
                } else {
                    mAdapter.addData(it.showSuccess!!)
                }
            }
        }
        //移除已经踢出的成员
        observeObject(KeyHelper.REFRESHING_SERVER_LIST2, this, ServiceMemberEntity::class.java) {
            mAdapter.data.find { it.userId == userId }?.run {
                mAdapter.remove(this)
            }
        }
    }

    override fun onRefresh(@NonNull refreshLayout: RefreshLayout) {
        launchRequest(true)
    }

    override fun onLoadMore() {
        launchRequest(false)
    }

    private fun launchRequest(isRefresh: Boolean, nickName: String? = null) {
        findMemberUseApiViewModel.requestGeneralListData(
                requiredParameter = RequestBodyParameter(
                        serverId = mRequestBodyParameter.serverId,
                        nickName = nickName
                ), isRefresh = isRefresh
        )
    }

    override fun onItemClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {
        val data = adapter.data[position] as ServiceMemberEntity
        data.serverName = mRequestBodyParameter.serverName
        nav(R.id.action_searchMemberUseApiFragment_to_editMemberFragment, Bundle().apply {
            putParcelable(BUNDLE_DATA, data)
        })
    }

    override fun onReload() {
        launchRequest(false)
    }

    override fun onClick(v: View) {
        actionLeft()
    }

    override val mRecyclerView: RecyclerView
        get() = dataBinding.rvMembers

    override fun provideAdapter(): BaseQuickAdapter<ServiceMemberEntity, BaseViewHolder> =
            RecommendationServerAdapter().apply {
                mAdapter = this
            }

    internal class RecommendationServerAdapter :
            BaseQuickAdapter<ServiceMemberEntity, BaseViewHolder>(R.layout.item_member),
            LoadMoreModule {

        override fun convert(holder: BaseViewHolder, item: ServiceMemberEntity) {
            setImageUrl(
                    holder.getView(R.id.ivAvatar),
                    item.avatar.imgUrl(),
                    placeholder = R.drawable.user_default_icon,
                    isCircle = true
            )
            holder.setText(R.id.tvNickname, item.nickName)
        }
    }

}




